<template>
  <div class="login_container">
    <el-row>
      <el-col :span="12" :xs="0"></el-col>
      <el-col :span="12" :xs="24">
        <el-form class="login_form" :model="loginForm" :rules="rules" ref="loginRef">
          <h1>Hello</h1>
          <h2>欢迎来到硅谷甄选</h2>
          <el-form-item prop="username">
            <el-input :prefix-icon="User" v-model="loginForm.username"></el-input>
          </el-form-item>
          <el-form-item prop="password">
            <el-input
              type="password"
              :prefix-icon="Lock"
              v-model="loginForm.password"
              show-password
            ></el-input>
          </el-form-item>
          <el-form-item>
            <el-button
              class="login_btn"
              type="primary"
              size="default"
              @click="login(loginRef)"
              :loading="loading"
              >登录</el-button
            >
          </el-form-item>
        </el-form>
      </el-col>
    </el-row>
  </div>
</template>

<script setup lang="ts">
import { User, Lock } from '@element-plus/icons-vue'
import { reactive, ref } from 'vue'
import useUserStore from '@/store/modules/user'
import { useRouter, useRoute } from 'vue-router'
import { ElNotification } from 'element-plus'
import { getTime } from '@/utils/time'
import type { FormInstance, FormRules } from 'element-plus'

let useStore = useUserStore()
let $router = useRouter()
let $route = useRoute()
//收集账号密码
let loginForm = reactive({ username: 'admin', password: '111111' })
// let loginForm = reactive({ username: '', password: '' })
let loading = ref(false)

//获取el-form组件
let loginRef = ref<FormInstance>()

const validateUsername = (rule: any, value: any, callback: any) => {
  //可以写一些正则
  if (value && value.length >= 4 && value.length <= 8) {
    callback()
  } else {
    callback(new Error('用户名长度必须4-8位'))
  }
}

const validatePassword = (rule: any, value: any, callback: any) => {
  if (value && value.length >= 6 && value.length <= 10) {
    callback()
  } else {
    callback(new Error('密码长度必须6-10位'))
  }
}

const rules = reactive<FormRules<typeof loginForm>>({
  username: [{ validator: validateUsername, trigger: 'change' }],
  password: [{ validator: validatePassword, trigger: 'change' }]
})

//登录按钮的回调
const login = async (formEl: FormInstance | undefined) => {
  // 要保证全部表单项校验通过再发请求
  if (!formEl) return
  await formEl.validate()

  loading.value = true
  //通知仓库发登录请求
  //请求成功->路由跳转
  //请求失败->弹出登陆失败信息
  try {
    await useStore.userLogin(loginForm)
    // 判断登录的时候，路由路径当中是否有query参数,如果有，就往query参数跳转；没有，就往首页跳转
    let redirect = $route.query.redirect as string
    $router.push({
      path: redirect ? redirect : '/'
    })
    ElNotification({
      type: 'success',
      message: '欢迎回来',
      title: `Hi,${getTime()}好！`
    })
    loading.value = false
  } catch (error) {
    loading.value = false
    ElNotification({
      type: 'error',
      message: (error as Error).message
    })
  }
}
</script>

<style scoped lang="scss">
.login_container {
  width: 100%;
  height: 100vh;
  background: url('@/assets/images/background.jpg') no-repeat;
  background-size: cover;

  .login_form {
    position: relative;
    width: 80%;
    top: 30vh;
    background: url('@/assets/images/login_form.png') no-repeat;
    background-size: cover;
    padding: 40px;

    h1 {
      color: white;
      font-size: 40px;
    }

    h2 {
      color: white;
      font-size: 20px;
      margin: 20px 0px;
    }

    .login_btn {
      width: 100%;
    }
  }
}
</style>
